package _18_剑指OfferII;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _082_剑指OfferII含有重复元素集合的组合 {


    public static void main(String[] args) {

        _082_剑指OfferII含有重复元素集合的组合 v = new _082_剑指OfferII含有重复元素集合的组合();


        int[] ins = {10, 1, 2, 7, 6, 1, 5};
        List<List<Integer>> lists = v.combinationSum2(ins, 8);

        for (List<Integer> list : lists) {
            System.out.println(list);
        }

    }

    private List<List<Integer>> results = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);

        dfs(candidates, 0, new ArrayList<>(), target);

        return results;
    }

    private void dfs(int[] candidates, int index, List<Integer> integers, int target) {
        if (target == 0) {
            results.add(new ArrayList<>(integers));
            return;
        }

        int len = candidates.length;
        for (int i = index; i < len; i++) {
            // 排除重复元素
            if (i > index && candidates[i] == candidates[i - 1]) continue;
            if (target - candidates[i] < 0) break;
            integers.add(candidates[i]);
            dfs(candidates, i + 1, integers, target - candidates[i]);
            integers.remove(integers.size() - 1);
        }
    }

}
